package w3_c2_queue;

public class LinkedListQueue <E> implements Queue<E>{

    /**
     * 定义内部节点类。
     */
    private class Node{
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }
        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    private  Node head, tail;
    private int size;

    public LinkedListQueue() {
        this.head = this.tail = null;
        this.size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enqueue(E e) {
        Node newNode = new Node(e, null);
        if(isEmpty()){
           head = tail = newNode;
        }
        else {
            tail.next = newNode;
            tail = newNode;//忘了这句了。写的时候时刻应该记得每个变量的不变的含义，即循环不变量。
        }
        size ++;
    }

    @Override
    public E dequeue() {
        if(isEmpty())
            throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        Node res = head;
        head = head.next;
        if(head == null)//忘了这句。删除到最后一个元素时，会影响tail指针。
            tail = null;
        size--;
        return res.e;
    }

    @Override
    public E getFront() {
        if(isEmpty())
            throw new IllegalArgumentException("Cannot dequeue from an empty queue");
        return head.e;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
//        res.append("LinkedListQueue, size = " + size + "\n");
        res.append("Queue: front [");
        for(Node p = head; p!= null; p = p.next)
            res.append(p.toString() + "->");
//        res.append("NULL");
//        res.append("] end"); //这两句可以合一
        res.append("NULL] end");
       return res.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue<Integer> queue = new LinkedListQueue<>();
        int i , n=10;
        System.out.println("\n--------Enqueue test---------");
        for (i = 0; i < n; i++) {
            queue.enqueue(i);
            System.out.println(String.format("Enqueue element %d, %s",i,queue));
        }

        System.out.println("\n--------Dequeue test---------");
        for (i = 0; i < n; i++) {
            Integer e = queue.dequeue();
            System.out.println(String.format("Dequeue element %d, %s",e,queue));
        }

    }
}
